package cn.relx.system.service.impl;

import cn.relx.system.domain.Role;
import cn.relx.system.mapper.RoleMapper;
import cn.relx.system.service.IRoleService;
import cn.relx.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author relx
 * @since 2022-10-24
 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public void add(Role role) {
        //保存角色信息，需要返回主键，用于保存中间表信息
        roleMapper.add(role);
        //保存主表数据之后，同步操作关联表
        initRelationTable(role);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        Role role = roleMapper.findByRoleId(id);
        roleMapper.delete(id);
        roleMapper.removeRoleMenu(role.getId());
        roleMapper.removeRolePermission(role.getId());
    }

    @Override
    @Transactional
    public void update(Role role) {
        roleMapper.update(role);
        initRelationTable(role);
    }

    public void initRelationTable(Role role){
        //由于我们并不知道用户是否添加角色的菜单、角色、或者是否取消角色的菜单、角色
        //那么我们最好的方案就是把角色对应的菜单、权限全部删除。再重新添加
        //删除角色对应的菜单
        roleMapper.removeRoleMenu(role.getId());
        //删除角色对应的权限
        roleMapper.removeRolePermission(role.getId());
        //删除成功之后再往中间表中批量添加数据
        //批量添加角色菜单中间表
        roleMapper.addRoleMenu(role.getId(),role.getMenus());
        //批量添加角色权限中间表
        roleMapper.addRolepermission(role.getId(),role.getPermissions());
    }

}
